<?php
// 本类由系统自动生成，仅供测试用途
class CommonAction extends Action {


	public function  __construct(){
    parent::__construct();
		$result1 ='test1';
		$this->result1 = $result1;
    $this->mapak=C('SET_MAP_AK');
        ////echo GROUP_NAME,MODULE_NAME,ACTION_NAME;
    //当前操作的请求                 分组名称/模块名/方法名
    // $url=GROUP_NAME.'/'.MODULE_NAME.'/'.ACTION_NAME;
    //$url=strtolower($url);//大写转成小写
    $now_group=GROUP_NAME;///分组名称
    $now_group=strtolower($now_group);//大写转成小写
    if($now_group=='index'){
      if(is_mobile()){
        redirect(U("Wap/Index/Index"));
      }
    }
    if(!IS_AJAX){
      $this->get_webseting();
    }
	}
	/**
     * 获得网站设置
     */
  public function get_webseting(){
     if(!IS_AJAX){
        $model=M('sys_param');
       $webseting['web_title']=$model->where(array('param_code'=>'web_title'))->getField('param_value'); 
       $webseting['web_copyright']=$model->where(array('param_code'=>'web_copyright'))->getField('param_value'); 
       $this->webseting=$webseting;
     }
  }
	/**
     * 获得树状结构数组
     * $arr必带 $arr['id'] $arr['pid']  
     */
	public function gettree($arr=array(),$pid=0,$lv=0,$field='pid',$f_field='id'){
      $returnarr=array();
      if(!empty($arr)){
      	 foreach ($arr as $key => $value) {
	       	if($pid==$value[$field]){
	       		unset($arr[$key]);
               $value['tree']=$this->gettree($arr,$value[$f_field],$lv++,$field,$f_field);
               $returnarr[]=$value;
	       	}else{
	       	   if($pid==$value[$f_field]){
	       	   	   unset($arr[$key]);
	               $value['tree']=$this->gettree($arr,$value[$f_field],$lv++,$field,$f_field);
	               $returnarr[]=$value;
	       	   }
	       	}
	      }
      }
      return $returnarr;
	}
///图片上传
		public function upload(){
		$path='./Uploads/';
		$years=Date("Y");
		$moth=Date("m");
		$day=Date("d");
		$path=$path."{$years}/";
		if (!is_dir("{$path}")) mkdir("{$path}"); // 如果不存在则创建
		$path=$path."{$moth}/";
		if (!is_dir("{$path}")) mkdir("{$path}"); // 如果不存在则创建
		$path=$path."{$day}/";
		if (!is_dir("{$path}")) mkdir("{$path}"); // 如果不存在则创建
		 import('ORG.Net.UploadFile');
		 $upload = new UploadFile();// 实例化上传类
		 $upload->maxSize  = 3145728 ;// 设置附件上传大小
		 $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		 $upload->savePath =  $path;// 设置附件上传目录
		 if(!$upload->upload()) {// 上传错误提示错误信息
			if(IS_AJAX){
				$this->ajaxReturn($data,$upload->getErrorMsg(),0);
				exit();
			}
			$this->error($upload->getErrorMsg());
		 }else{// 上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();
		 }
		 return $info;
	}

	///图片上传
		public function upload_ajax(){

		$path='./Uploads/';
		$years=Date("Y");
		$moth=Date("m");
		$day=Date("d");
		$path=$path."{$years}/";
		if (!is_dir("{$path}")) mkdir("{$path}"); // 如果不存在则创建
		$path=$path."{$moth}/";
		if (!is_dir("{$path}")) mkdir("{$path}"); // 如果不存在则创建
		$path=$path."{$day}/";
		if (!is_dir("{$path}")) mkdir("{$path}"); // 如果不存在则创建
		 import('ORG.Net.UploadFile');
		 $upload = new UploadFile();// 实例化上传类
		 $upload->maxSize  = 3145728 ;// 设置附件上传大小
		 $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		 $upload->savePath =  $path;// 设置附件上传目录
		 if(!$upload->upload()) {// 上传错误提示错误信息
			if(IS_AJAX){
				$this->ajaxReturn($data,$upload->getErrorMsg(),0);
				exit();
			}
			$this->error($upload->getErrorMsg());
		 }else{// 上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();
		 }
		 $data['error']='';//成功
		 $data['msg']='0000';//成功
		 $data['imgurl']=$info[0]['savepath'].$info[0]['savename'];//成功
		 $data['imgurl']=substr($data['imgurl'],1);//去掉点
		 echo json_encode($data);
	}
	//托截取上传
	public function crop_submit(){
         $_REQUEST['x']=round($_REQUEST['x']);  
		 $_REQUEST['y']=round($_REQUEST['y']);
		 $_REQUEST['w']=round($_REQUEST['w']);
		 $_REQUEST['h']=round($_REQUEST['h']);
		 $targ_w = round($_REQUEST['w']);
		 $targ_h = round($_REQUEST['h']);
		 $jpeg_quality = 90;
		 $pic_name = $_REQUEST['pic_name'];
		 $src = '.'.$pic_name;
	     $pic_type=explode('.', $pic_name);
	     $type=$pic_type[1];

	     $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
	     if(!function_exists($createFun)) {
	       	 $data['status']=0;
	       	 $data['error']='缩略图创建失败';
	       	 echo json_encode($data);die;
	       }
	        $img_r = $createFun($src);
		  // $img_r = imagecreatefromjpeg($src);
		 $dst_r = imagecreatetruecolor( $targ_w, $targ_h );
		  // imagecopy( $target, $source, 0, 0, $x, $y, $w, $h);
          if (function_exists("ImageCopyResampled"))
              imagecopyresampled($dst_r,$img_r,0,0,$_REQUEST['x'],$_REQUEST['y'],$targ_w,$targ_h,$_REQUEST['w'],$_REQUEST['h']);
          else
              imagecopyresized($dst_r,$img_r,0,0,$_REQUEST['x'],$_REQUEST['y'],$targ_w,$targ_h,$_REQUEST['w'],$_REQUEST['h']);
            
		 //imagecopyresampled($dst_r,$img_r,0,0,$_REQUEST['x'],$_REQUEST['y'],$targ_w,$targ_h,$_REQUEST['w'],$_REQUEST['h']);
         //header("content-type: image/jpg");
		 //var_dump($dst_r);die;
         $pic_name='.'.$pic_type[0].rand(1000,9999).'.'.$pic_type[1];
		 //生成图片
	     $re=imagejpeg($dst_r,$pic_name,$jpeg_quality);
        imagedestroy($dst_r);
		imagedestroy($img_r);
	     $data['status']=0;
	     if($re){
	     	if(file_exists($src)){
	     		unlink($src);//删除原文件
	     	}
	     	$data['status']=1;
	     	$data['file']=substr($pic_name,1);
	     }else{
	     	$data['error']='缩略图创建失败';
	     }
	     echo json_encode($data);

	}
	//检测验证码
	public function checkVerify(){
		if($_SESSION['verify'] != md5($_REQUEST['verify_code'])) {
			echo 0;
		}else{
			echo 1;
		}
	}
	//检测验证码
	public function checkVerify_return(){
		if($_SESSION['verify'] != md5($_REQUEST['verify_code'])) {
			return false;
		}else{
			return true;
		}
	}
	//生成验证码
	public function verify(){
		import('ORG.Util.Image');
		Image::buildImageVerify();
	}
   //获取缩略图
   public function get_thumbs(){
        $imgurl=$_GET['img'];
         $width=$_GET['w'];
        $height=$_GET['h'];
        if($_GET['auto']){
          $width=$_GET['auto'];
          $height=$_GET['auto'];
        }
        thumbs_auto($imgurl,$width,$height);
   }
    //短信验证码验证 注册
   public function check_send_reg(){
   	$data['status']=0;
   	    $send=$_SESSION['send'];
   	    if(empty($send)){
           $data['msg']="短信验证码错误";
           echo 0;die;
   	    }
   	    $time=time();
   	    $s_time=$time-$send['add_time'];
   	    if($s_time>60*10){//10分钟
          $data['msg']="短信验证码已过期请重新获取";
          echo 0;die;
   	    }
		$mobile=$_REQUEST['mobile'];
        if(empty($mobile) || $mobile!=$send['mobile']){
        	$data['msg']="手机号码不匹配";
        	 echo 0;die;
        }
        $code=$_REQUEST['mobile_code'];
        if(empty($code) || $code!=$send['code']) {
			$data['msg']="验证码错误";
        	 echo 0;die;
		}
		//unset($_SESSION['send']);
		//发送成功
        $data['status']=1;
        $data['msg']="短信验证码验证通过";
        $data['code']=$code;

         echo 1;die;
    }
   //短信验证码验证 注册
   public function check_send_return(){
   	$data['status']=0;
   	    $send=$_SESSION['send'];
   	    if(empty($send)){
           $data['error']="短信验证码错误";
           return $data;
   	    }
   	    $time=time();
   	    $s_time=$time-$send['add_time'];
   	    if($s_time>60*10){//10分钟
          $data['error']="短信验证码已过期请重新获取";
          return $data;
   	    }
		$mobile=$_REQUEST['mobile'];
        if(empty($mobile) || $mobile!=$send['mobile']){
        	$data['error']="手机号码不匹配";
        	return $data;
        }
        $mobile_code=$_REQUEST['mobile_code'];
        if(empty($mobile_code) || $mobile_code!=$send['code']) {
			$data['error']="验证码错误";
        	return $data;
		}
		//unset($_SESSION['send']);
		//发送成功
        $data['status']=1;
        return $data;
    }
   //短信验证码验证
   public function check_send_ajax(){
   	$data['status']=0;
   	    $send=$_SESSION['send'];
   	    if(empty($send)){
           $data['msg']="短信验证码错误";
           echo json_encode($data);die;
   	    }
   	    $time=time();
   	    $s_time=$time-$send['add_time'];
   	    if($s_time>60*10){//10分钟
          $data['msg']="短信验证码已过期请重新获取";
          echo json_encode($data);die;
   	    }
		$mobile=$_REQUEST['mobile'];
        if(empty($mobile) || $mobile!=$send['mobile']){
        	$data['msg']="手机号码不匹配";
        	echo json_encode($data);die;
        }
        $code=$_REQUEST['mobile_code'];
        if(empty($code) || $code!=$send['code']) {
			$data['msg']="验证码错误";
        	echo json_encode($data);die;
		}
		//unset($_SESSION['send']);
		//发送成功
        $data['status']=1;
        $data['msg']="短信验证码验证通过";
        $data['code']=$code;

        echo json_encode($data);die;
    }
    //短信验证码验证
   public function check_send(){
   	$data['status']=0;
   	    $send=$_SESSION['send'];
   	    if(empty($send)){
           $data['msg']="短信验证码错误";
           return $data;
   	    }
   	    $time=time();
   	    $s_time=$time-$send['add_time'];
   	    if($s_time>60*10){//10分钟
          $data['msg']="短信验证码已过期请重新获取";
          return $data;
   	    }
		$mobile=$_REQUEST['mobile'];
        if(empty($mobile) || $mobile!=$send['mobile']){
        	$data['msg']="手机号码不匹配";
        	return $data;
        }
        $code=$_REQUEST['mobile_code'];
        if(empty($code) || $code!=$send['code']) {
			$data['msg']="验证码错误";
        	return $data;
		}
		//unset($_SESSION['send']);
		//发送成功
        $data['status']=1;
        $data['msg']="短信验证码验证通过";
        $data['code']=$code;

        return $data;
    }
   //短信发送
   public function send_sms(){
   	    $data['status']=0;
   	    $send=$_SESSION['send'];
   	    $time=time();
   	    $s_time=$time-$send['add_time'];
   	    if($s_time<60){
          $data['msg']="短信发送太频繁，请前后间隔60秒";
          echo json_encode($data);die;
   	    }
		$mobile=$_REQUEST['mobile'];
        if(empty($mobile) || check_phone($mobile)===false){
        	$data['msg']="手机号码错误";
        	echo json_encode($data);die;
        }
        if($_SESSION['verify'] != md5($_REQUEST['verify_code'])) {
			$data['msg']="验证码错误";
        	echo json_encode($data);die;
		}
		$code=rand(100000,999999);
	    $mseeage="您的短信验证码为：{$code}。";
       //$res=//发送短信
       $send=$this->sendSMS($mobile,$mseeage);
       $send_status=0;
       if($send['status']==1){
          $send_status=1;
          //发送成功
          $data['status']=1;
          $data['msg']="短信发送成功";
          $data['code']=$code;
           //存入session
          $s_data['mobile']=$mobile;
          $s_data['add_time']=$time;
          $s_data['code']=$code;
          $_SESSION['send']=$s_data;
       }


        //存入数据库
        $send_data=$s_data;
        $send_data['message']=$message;
        $send_data['status']=1;
        M("send_log")->add($send_data);

        echo json_encode($data);die;
    }
    //短信发送
   public function send_sms_findpwd(){
        $data['status']=0;
        $send=$_SESSION['send'];
        $time=time();
        $s_time=$time-$send['add_time'];
        if($s_time<60){
          $data['msg']="短信发送太频繁，请前后间隔60秒";
          echo json_encode($data);die;
        }
        $mobile=$_REQUEST['mobile'];
        if(empty($mobile) || check_phone($mobile)===false){
          $data['msg']="手机号码错误";
          echo json_encode($data);die;
        }
        /*if($_SESSION['verify'] != md5($_REQUEST['verify_code'])) {
          $data['msg']="验证码错误";
              echo json_encode($data);die;
        }*/
         $count=M('member')->where(array('mobile'=>$mobile))->count();
        if(empty($count)){
          $data['msg']="手机号未注册";
          echo json_encode($data);die;
        }
      $code=rand(100000,999999);
      $mseeage="您的短信验证码为：{$code}。";
       //$res=//发送短信
       $send=$this->sendSMS($mobile,$mseeage);
       $send_status=0;
       if($send['status']==1){
          $send_status=1;
          //发送成功
          $data['status']=1;
          $data['msg']="短信发送成功";
          $data['code']=$code;
           //存入session
          $s_data['mobile']=$mobile;
          $s_data['add_time']=$time;
          $s_data['code']=$code;
          $_SESSION['send']=$s_data;
       }else{
         $data['msg']=$send['error'];
       }

        //存入数据库
        $send_data=$s_data;
        $send_data['message']=$message;
        $send_data['status']=$send_status;
        M("send_log")->add($send_data);

        echo json_encode($data);die;
    }
      //短信发送
   public function send_sms_fastreg(){
        $data['status']=0;
        $send=$_SESSION['send'];
        $time=time();
        $s_time=$time-$send['add_time'];
        if($s_time<60){
          $data['msg']="短信发送太频繁，请前后间隔60秒";
          echo json_encode($data);die;
        }
        $mobile=$_REQUEST['mobile'];
        if(empty($mobile) || check_phone($mobile)===false){
          $data['msg']="手机号码错误";
          echo json_encode($data);die;
        }
        $count=M('member')->where(array('mobile'=>$mobile))->count();
        if($count>0){
          $data['msg']="手机号已注册";
          echo json_encode($data);die;
        }
        /*if($_SESSION['verify'] != md5($_REQUEST['verify_code'])) {
          $data['msg']="验证码错误";
              echo json_encode($data);die;
        }*/
      $code=rand(100000,999999);
      $mseeage="您的短信验证码为：{$code}。";
       //$res=//发送短信
       $send=$this->sendSMS($mobile,$mseeage);
       $send_status=0;
       if($send['status']==1){
          $send_status=1;
          //发送成功
          $data['status']=1;
          $data['msg']="短信发送成功";
          $data['code']=$code;
           //存入session
          $s_data['mobile']=$mobile;
          $s_data['add_time']=$time;
          $s_data['code']=$code;
          $_SESSION['send']=$s_data;
       }
        //存入数据库
        $send_data=$s_data;
        $send_data['message']=$message;
        $send_data['status']=1;
        M("send_log")->add($send_data);

        echo json_encode($data);die;
    }
    //获取城市 信息
    public function get_city(){
    	$province=$_REQUEST['province'];//获取省份信息
    	$provinceid=$_REQUEST['provinceid'];//获取城市信息
    	$cityid=$_REQUEST['cityid'];//获取区县 信息
       //$citylist=array("province"=>1,"provinceid"=>0,"cityid"=>0
        $city=array('province'=>$province,'provinceid'=>$provinceid,'cityid'=>$cityid);
        $citylist=getcitylist($city);
        $return="";
        foreach ($citylist as $key => $value) {
        	$return=$citylist[$key];
        }
        unset($citylist);
        echo  json_encode($return);
    }
    //获取城市 信息
    public function get_city_return($data=array('province'=>1,'provinceid'=>0,'cityid'=>0)){
       //$citylist=array("province"=>1,"provinceid"=>0,"cityid"=>0
        $city=array();
        $citylist=getcitylist($data);
        return $citylist;
    }
    ///记录用户消费日志 消费记录
    /*$log_data['type']=3;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
     *       $log_data['member_id']=$this->uid;
      *      $log_data['money']=$money;
      *      $log_data['status']=2;//状态 1收入 2支出
      *      $log_data['des']="申请提现扣除金额￥".$money;//消费介绍
      *     $log_data['add_time']=time();//消费时间
      */
    public function set_member_consume_record($data=array()){
       if(empty($data)){
        return false;
       }
        return M('member_consume_record')->add($data);
    }
     ///记录商户消费日志 消费记录  type 消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
   /*   $log_data['type']=3;//消费类型 1订单消费 2充值 3提现    4退款 
     *         $log_data['shop_id']=session('afid');
     *         $log_data['money']=$money;
     *         $log_data['status']=2;//状态 1收入 2支出
     *         $log_data['des']="申请提现扣除金额￥".$money;//消费介绍
     *         $log_data['add_time']=time();//消费时间
     */
    public function set_shop_consume_record($data=array()){
       if(empty($data)){
        return false;
       }
       return M('shop_consume_record')->add($data);
    }
         ///记录用户积分日志 消费记录  type 消费类型 1获得 2消费
   /*   $log_data['type']=3;//消费类型 1获得 2消费
     *         $log_data['member_id']=$member_id;
     *         $log_data['integral']=$integral;
     *         $log_data['status']=2;//状态 1收入 2支出
     *         $log_data['des']="申请提现扣除金额￥".$money;//消费介绍
     *         $log_data['add_time']=time();//消费时间
     */
    public function set_member_integral($data=array()){
       if(empty($data)){
        return false;
       }
       return M('member_integral')->add($data);
    }
   ///加减余额 记录日志 $status 1 收入 2支持  money
   /*   $log_data['type']=3;//消费类型 1订单消费 2充值 3提现    4退款 
     *         $log_data['shop_id']=session('afid');
     *         $log_data['money']=$money;
     *         $log_data['status']=2;//状态 1收入 2支出
     *         $log_data['des']="申请提现扣除金额￥".$money;//消费介绍
     *         $log_data['add_time']=time();//消费时间
     */
    public function set_member_balance($member_id=0,$status=0,$money=0,$log=array()){
       if(empty($member_id) || !in_array($status, array(1,2))|| empty($money) || $money<0 || empty($log)){
         return false;
        }
        $consume_record_model=M('member_consume_record');
        $member_detail_model=M('member_detail');
        $field="member_id,points,balance";
        $where['member_id']=$member_id;
        $memberinfo=$member_detail_model->Where($where)->field($field)->find();
        if(empty($memberinfo)){
          return false;
        }
        if($status==1){//收入
            $m_s_data['balance']=$memberinfo['balance']+$money;
        }else{
             $m_s_data['balance']=$memberinfo['balance']-$money;
        }
        $log['status']=$status;
        $log['add_time']=time();
        $log['member_id']=$member_id;
        $log['money']=$money;
         $member_detail_model->startTrans();//开起事务
        $consume_record_model->startTrans();//开起事务

        $m_res=$member_detail_model->where($where)->save($m_s_data);
        $c_res=$consume_record_model->add($log);
        if($c_res!==false && $m_res!==false){
            $consume_record_model->commit();//提交事务
            $member_detail_model->commit();//提交事务

            return true;
        }else{
            $member_detail_model->rollback();//回滚事务
            $consume_record_model->rollback();//回滚事务

            return false;
        }
    }
 ///加减积分 记录日志 $status 1 收入 2支持  integral 积分
   /*   $log_data['type']=3;//消费类型 1订单消费 2充值 3提现    4退款 
     *         $log_data['shop_id']=session('afid');
     *         $log_data['money']=$money;
     *         $log_data['status']=2;//状态 1收入 2支出
     *         $log_data['des']="申请提现扣除金额￥".$money;//消费介绍
     *         $log_data['add_time']=time();//消费时间
     */
    public function set_member_points($member_id=0,$status=0,$integral=0,$log=array()){
       if(empty($member_id) || !in_array($status, array(1,2))|| empty($integral) || $integral<0 || empty($log)){
         return false;
        }
        $member_integral=M('member_integral');
        $member_detail_model=M('member_detail');
        $field="member_id,points,balance";
        $where['member_id']=$member_id;
        $memberinfo=$member_detail_model->Where($where)->field($field)->find();
        if(empty($memberinfo)){
          return false;
        }
        if($status==1){//收入
            $m_s_data['points']=$memberinfo['points']+$integral;
        }else{
            $m_s_data['points']=$memberinfo['points']-$integral;
        }
        $log['status']=$status;
        $log['type']=$status;
        $log['add_time']=time();
        $log['member_id']=$member_id;
        $log['integral']=$integral;
        $member_detail_model->startTrans();//开起事务
        $member_integral->startTrans();//开起事务

        $m_res=$member_detail_model->where($where)->save($m_s_data);
        $c_res=$member_integral->add($log);
        if($c_res!==false && $m_res!==false){
            $member_integral->commit();//提交事务
            $member_detail_model->commit();//提交事务

            return true;
        }else{
            $member_detail_model->rollback();//回滚事务
            $member_integral->rollback();//回滚事务
            
            return false;
        }
    }
//定时发送
/*
$time = '2010-05-27 12:11';
$res = sendSMS($uid,$pwd,$mobile,$content,$time);
echo $res;
*/
function sendSMS($mobile,$content,$time='',$mid='')
{
  $http = 'http://http.yunsms.cn/tx/';//接口地址 'http://接口地址/tx/';
  $data = array
    (
    'uid'=>'56696',          //用户账号
    'pwd'=>strtolower(md5('j4h4qq')), //MD5位32密码
    'mobile'=>$mobile,        //号码
    'content'=>$content,      //内容 如果对方是utf-8编码，则需转码iconv('gbk','utf-8',$content); 如果是gbk则无需转码
    'time'=>$time,    //定时发送
    'mid'=>$mid,           //子扩展号
    'encode'=>'utf8'
    );
  $re= $this->postSMS($http,$data);      //POST方式提交
  $return_data['status']=0;
  if( trim($re) == '100' )
  {
    $return_data['status']=1;
    return $return_data;
  }
  else 
  {
    //return "发送失败! 状态：".$re;
    $return_data['error']="短信发送失败，请稍后再试";
    return $return_data;
  }
}    
public function postSMS($url,$data='')
{
  $post='';
  $row = parse_url($url);
  $host = $row['host'];
  $port = $row['port'] ? $row['port']:80;
  $file = $row['path'];
  while (list($k,$v) = each($data)) 
  {
    $post .= rawurlencode($k)."=".rawurlencode($v)."&"; //转URL标准码
  }
  $post = substr( $post , 0 , -1 );
  $len = strlen($post);
  $fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
  if (!$fp) {
    return "$errstr ($errno)\n";
  } else {
    $receive = '';
    $out = "POST $file HTTP/1.0\r\n";
    $out .= "Host: $host\r\n";
    $out .= "Content-type: application/x-www-form-urlencoded\r\n";
    $out .= "Connection: Close\r\n";
    $out .= "Content-Length: $len\r\n\r\n";
    $out .= $post;    
    fwrite($fp, $out);
    while (!feof($fp)) {
      $receive .= fgets($fp, 128);
    }
    fclose($fp);
    $receive = explode("\r\n\r\n",$receive);
    unset($receive[0]);
    return implode("",$receive);
  }
}
  
}